package work.javac.common;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class JarLoader {

    private static final String LIB = "lib";

    public static void init() throws NoSuchMethodException, MalformedURLException, IllegalAccessException, InvocationTargetException {
        File directory =  PathUtil.getFile(LIB);
        if(!directory.exists()){
            directory.mkdir();
        }
        File[] jars = directory.listFiles();
        for (File file : jars) {
            if (file.getPath().endsWith(".jar")) {
                addUrl(file);
            }
        }
    }


    public static void addUrl(File jarPath) throws NoSuchMethodException, MalformedURLException, InvocationTargetException, IllegalAccessException {
        URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        URL url = jarPath.toURI().toURL();
        method.invoke(classLoader, url);
    }

}
